package com.example.wxy.bbtapp.DeviceService;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import com.example.wxy.bbtapp.Common.ListHelper;
import com.example.wxy.bbtapp.Startup.AppSettings;
import com.example.wxy.bbtapp.Models.CourseRecord.ProcessRecord;
import com.example.wxy.bbtapp.myApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by yons on 2017/9/5.
 * 取电池显示里app操作记录
 */

public class AppMonitorService {

    public static final int AID_APP = 10000;
    public static final int AID_USER = 100000;

//
//    String getTopPackage(UsageStatsManager mUsageStatsManager){
//        long ts = System.currentTimeMillis();
//        //UsageStatsManager mUsageStatsManager = (UsageStatsManager)getSystemService("usagestats");
//        List<UsageStats> usageStats = null;
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//            usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts-1000, ts);
//        }
//        if (usageStats == null || usageStats.size() == 0) {
//            return "";
//        }
//        //Collections.sort(usageStats, mRecentComp);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            return usageStats.get(0).getPackageName();
//        }
//        return "";
//    }

    public static String getTopActivy(Context c)
    {
        ActivityManager manager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(Integer.MAX_VALUE);
        List<String> tasks = new ArrayList<String>();
        String PackageName = "";
        if(runningTaskInfos.size() > 0)
            PackageName = runningTaskInfos.get(0).baseActivity.getPackageName();
        return PackageName;
    }

    public static List<ProcessRecord> getTopActivy(Context context, final List<ProcessRecord> processList, int CourseID)
    {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(Integer.MAX_VALUE);
        List<String> tasks = new ArrayList<String>();
        for(int i=0;i<runningTaskInfos.size(); i++)
        {
            final String PackageName = runningTaskInfos.get(i).baseActivity.getPackageName();
            ProcessRecord pr = new ListHelper<ProcessRecord>().FindFirst(processList, new ListHelper.Expression<ProcessRecord>() {
                @Override
                public boolean where(ProcessRecord org) {
                    return org.whitelist_id.equals(PackageName);
                }
            });

            if(pr != null)
            {
                pr.user_date_secoend += AppSettings.MonitorSecond;
                continue;
            }
            else
            {
                pr = new ProcessRecord();
                pr.whitelist_id = PackageName;
                pr.user_date_secoend = AppSettings.MonitorSecond;
                pr.school_id = myApplication.bindinofs.getSchoolID();
                pr.course_record_id =CourseID;
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                pr.use_date = df.format(new Date());
                processList.add(pr);
            }
        }

        return processList;
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有包名的字符串列表
     */
    public static List<String> getHomes(Context c) {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = c.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo ri : resolveInfo) {
            names.add(ri.activityInfo.packageName);
        }
        return names;
    }




    public static List<String> getRunningApp(ActivityManager mActivityManager) {

        List<String> list = new ArrayList<String>();
        ArrayList<ActivityManager.RunningTaskInfo> appRunningTasks= (ArrayList<ActivityManager.RunningTaskInfo>) mActivityManager.getRunningTasks(50);
        System.out.println("***************getRunningTask********************");
        for(Iterator<ActivityManager.RunningTaskInfo> iterator = appRunningTasks.iterator(); iterator.hasNext();)
        {
            ActivityManager.RunningTaskInfo taskInfo=iterator.next();
            System.out.println(taskInfo.baseActivity.getClassName());
        }
        System.out.println("*************************************************");

        return list;
    }


    public static String getForegroundApp() {
        File[] files = new File("/proc").listFiles();
        int lowestOomScore = Integer.MAX_VALUE;
        String foregroundProcess = null;
        for (File file : files) {
            if (!file.isDirectory()) {
                continue;
            }
            int pid;

            try {
                pid = Integer.parseInt(file.getName());
            } catch (NumberFormatException e) {
                continue;
            }

            try {
                String cgroup = read(String.format("/proc/%d/cgroup", pid));
                String[] lines = cgroup.split("\n");
                String cpuSubsystem;
                String cpuaccctSubsystem;

                if (lines.length == 2) {// 有的手机里cgroup包含2行或者3行，我们取cpu和cpuacct两行数据
                    cpuSubsystem = lines[0];
                    cpuaccctSubsystem = lines[1];
                } else if (lines.length == 3) {
                    cpuSubsystem = lines[0];
                    cpuaccctSubsystem = lines[2];
                } else {
                    continue;
                }

                if (!cpuaccctSubsystem.endsWith(Integer.toString(pid))) {
                    // not an application process
                    continue;
                }
                if (cpuSubsystem.endsWith("bg_non_interactive")) {
                    // background policy
                    continue;
                }

                String cmdline = read(String.format("/proc/%d/cmdline", pid));
                if (cmdline.contains("com.android.systemui")) {
                    continue;
                }
                int uid = Integer.parseInt(cpuaccctSubsystem.split(":")[2]
                        .split("/")[1].replace("uid_", ""));
                if (uid >= 1000 && uid <= 1038) {
                    // system process
                    continue;
                }
                int appId = uid - AID_APP;
                int userId = 0;
                // loop until we get the correct user id.
                // 100000 is the offset for each user.

                while (appId > AID_USER) {
                    appId -= AID_USER;
                    userId++;
                }

                if (appId < 0) {
                    continue;
                }
                // u{user_id}_a{app_id} is used on API 17+ for multiple user
                // account support.
                // String uidName = String.format("u%d_a%d", userId, appId);
                File oomScoreAdj = new File(String.format(
                        "/proc/%d/oom_score_adj", pid));
                if (oomScoreAdj.canRead()) {
                    int oomAdj = Integer.parseInt(read(oomScoreAdj
                            .getAbsolutePath()));
                    if (oomAdj != 0) {
                        continue;
                    }
                }
                int oomscore = Integer.parseInt(read(String.format(
                        "/proc/%d/oom_score", pid)));
                if (oomscore < lowestOomScore) {
                    lowestOomScore = oomscore;
                    foregroundProcess = cmdline;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return foregroundProcess;

    }

    private static String read(String path) throws IOException {
        StringBuilder output = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(path));
        output.append(reader.readLine());

        for (String line = reader.readLine(); line != null; line = reader
                .readLine()) {
            output.append('\n').append(line);
        }
        reader.close();
        return output.toString().trim();// 不调用trim()，包名后会带有乱码
    }
}
